﻿using CPF;

using GeneralUpdate.Core;
using GeneralUpdate.Core.Bootstrap;
using GeneralUpdate.Core.Domain.Enum;
using GeneralUpdate.Core.Events.CommonArgs;
using GeneralUpdate.Core.Events.MultiEventArgs;
using GeneralUpdate.Core.Strategys.PlatformWindows;

using System;
using System.Text;
using System.Threading.Tasks;

namespace EHO.AutoUpdate.Upgrade.VModel
{
    /// <summary>主窗体的数据对象</summary>
    internal class MainWindowVM : CpfObject
    {
        #region 属性
        /// <summary>当前程序版本</summary>
        [PropertyMetadata("0.0")]
        public string CurrentVersion
        {
            get
            {
                return (string)GetValue();
            }
            set
            {
                SetValue(value);
            }
        }
        /// <summary>当前服务器上最新版本</summary>
        [PropertyMetadata("0.0")]
        public string NewVersion
        {
            get
            {
                return (string)GetValue();
            }
            set
            {
                SetValue(value);
            }
        }
        /// <summary>下载速度</summary>
        [PropertyMetadata("0.0")]
        public string Speed
        {
            get
            {
                return (string)GetValue();
            }
            set
            {
                SetValue(value);
            }
        }


        /// <summary>需要下载文件数量</summary>
        [PropertyMetadata(0)]
        public int DownLoadCount
        {
            get
            {
                return (int)GetValue();
            }
            set
            {
                SetValue(value);
            }
        }
        /// <summary>下载进度</summary>
        [PropertyMetadata(0)]
        public double DownLoadProcess
        {
            get
            {
                return (double)GetValue();
            }
            set
            {
                SetValue(value);
            }
        }

        /// <summary>下载数量与总量的比例</summary>
        [PropertyMetadata("0/0")]
        public string DownLoadRatio
        {
            get
            {
                return (string)GetValue();
            }
            set
            {
                SetValue(value);
            }
        }
        GeneralUpdateBootstrap _GeneralUpdateBootstrap { get; set; }
        #endregion

        public MainWindowVM(string[] args)
        {
            Task.Run(async () =>
            {
                _GeneralUpdateBootstrap = await new GeneralUpdateBootstrap()
                //单个或多个更新包下载通知事件
                .AddListenerMultiDownloadProgress(OnMultiDownloadProgressChanged)
                //单个或多个更新包下载速度、剩余下载事件、当前下载版本信息通知事件
                .AddListenerMultiDownloadStatistics(OnMultiDownloadStatistics)
                //单个或多个更新包下载完成
                .AddListenerMultiDownloadCompleted(OnMultiDownloadCompleted)
                //完成所有的下载任务通知
                .AddListenerMultiAllDownloadCompleted(OnMultiAllDownloadCompleted)
                //下载过程出现的异常通知
                .AddListenerMultiDownloadError(OnMultiDownloadError)
                //整个更新过程出现的任何问题都会通过这个事件通知
                .AddListenerException(OnException)
                .Remote(args[0])
                .Strategy<WindowsStrategy>()
                .Option(UpdateOption.Encoding, Encoding.Default)
                .Option(UpdateOption.DownloadTimeOut, 10 * 60)
                .Option(UpdateOption.Format, Format.ZIP)
                .LaunchTaskAsync();

            });
        }
        void OnMultiDownloadStatistics(object sender, MultiDownloadStatisticsEventArgs e)
        {
            //e.Remaining 剩余下载时间
            //e.Speed 下载速度
            //e.Version 当前下载的版本信息
            Speed = $"{e.Speed}";
        }

        void OnMultiDownloadProgressChanged(object sender, MultiDownloadProgressChangedEventArgs e)
        {
            //XTrace.WriteLine($"OnMultiDownloadProgressChanged - {e.ToJson()}");
            switch (e.Type)
            {
                case ProgressType.Check:
                case ProgressType.Download:
                    DownLoadProcess = Math.Round(e.ProgressPercentage * 100, 2);
                    DownLoadRatio = $"{e.BytesReceived}/{e.TotalBytesToReceive}";
                    //XTrace.WriteLine($" {Math.Round(e.ProgressPercentage * 100, 2)}% ， Receivedbyte：{e.BytesReceived}M ，Totalbyte：{e.TotalBytesToReceive}M");
                    break;

                case ProgressType.Updatefile:
                    //XTrace.WriteLine($" {Math.Round(e.ProgressValue * 100, 2)}% ， Receivedbyte：{e.BytesReceived}M ，Totalbyte：{e.TotalBytesToReceive}M");
                    break;

                case ProgressType.Done:
                    break;

                case ProgressType.Fail:
                    break;
            }
        }
        void OnMultiDownloadCompleted(object sender, MultiDownloadCompletedEventArgs e)
        {
            //var info = e.Version as VersionInfo;
            //XTrace.WriteLine($"{e.ToJson()} download completed.");
        }

        void OnMultiAllDownloadCompleted(object sender, MultiAllDownloadCompletedEventArgs e)
        {
            
        }

        void OnMultiDownloadError(object sender, MultiDownloadErrorEventArgs e)
        {
            //var info = e.Version as VersionInfo;
            //XTrace.WriteLine($"{info.Name},{e.Exception.Message}.");
        }

        void OnException(object sender, ExceptionEventArgs e)
        {
            //XTrace.WriteException(e.Exception);
        }
    }
}
